/*
 * Created by Jaren at 2021/10/28 17:49
 */
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:inmotion_protocol_example/module/base/base.dart';
import 'package:inmotion_protocol_example/module/search/search_controller.dart';

class SearchPage extends BaseView<LxSearchController> {
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
        appBar: AppBar(
          title: const Text("Scan Device"),
        ),
        body: Column(
          children: [
            Obx(
              () => InkWell(
                onTap: () {
                  _handleScanBtnClick(controller);
                },
                child: Container(
                  color: controller.isScan.value ? Colors.red : Colors.green,
                  width: 100,
                  height: 100,
                  child: Center(
                    child: Text(
                      controller.isScan.value ? 'STOP' : 'SCAN',
                      style: const TextStyle(
                          color: Color.fromARGB(0xFF, 0xFF, 0xFF, 0xFF)),
                    ),
                  ),
                ),
              ),
            ),
            Expanded(
              child: Obx(
                () => RefreshIndicator(
                  onRefresh: () async {
                    controller.isScan.value = false;
                    controller.devices.clear();
                  },
                  child: controller.isLoading.value
                      ? const CircularProgressIndicator(
                          strokeWidth: 5,
                        )
                      : _buildListView(controller),
                ),
              ),
            ),
          ],
        ));
  }

  _handleScanBtnClick(controller) {
    if (controller.isScan.value) {
      controller.devices.clear();
      controller.isScan.value = false;
      controller.stopScanning();
    } else {
      controller.isScan.value = true;
      controller.scan();
    }
  }

  _handleDeviceItemClick(controller, device) {
    controller.connect(device: device);
  }

  _buildListView(controller) {
    return ListView.builder(
      itemCount: controller.devices.length,
      itemBuilder: (context, index) {
        final item = controller.devices[index];
        return ListTile(
          onTap: () => _handleDeviceItemClick(controller, item),
          title: Text(item.name),
          subtitle: Text(item.id.id),
        );
      },
    );
  }
}
